/** @odoo-module **/

import { Component, useState, useRef, onMounted } from "@odoo/owl";
import { useService } from "@web/core/utils/hooks";
import { registry } from "@web/core/registry";
import { ActionContainer } from "@web/webclient/actions/action_container";

export class TabManager extends Component {
    static template = "web_layout_enhance.TabManager";
    static components = { ActionContainer };
    static props = {};

    setup() {
        this.actionService = useService("action");
        this.layoutConfig = useService("layoutConfig");
        
        this.state = useState({
            tabs: [],
            activeTabId: null,
        });

        // 监听 action 执行事件
        onMounted(() => {
            if (this.layoutConfig.isMultiTabEnabled()) {
                this._patchActionService();
            }
        });
    }

    _patchActionService() {
        console.log('[TabManager] Patching action service...');
        const originalDoAction = this.actionService.doAction.bind(this.actionService);
        this.actionService.doAction = async (action, options = {}) => {
            console.log('[TabManager] doAction called:', action, options);
            // 如果启用了多标签页且不是内部调用
            if (this.layoutConfig.isMultiTabEnabled() && !options._isTabManagerCall) {
                console.log('[TabManager] Creating new tab...');
                // 创建新标签页
                const tabId = `tab_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
                
                // 获取 action 的标题
                let title = 'New Tab';
                if (typeof action === 'object') {
                    title = action.display_name || action.name || action.xml_id || title;
                } else if (typeof action === 'string' || typeof action === 'number') {
                    title = `Action ${action}`;
                }
                
                console.log('[TabManager] Tab title:', title);
                
                // 添加标签页
                this.addTab({
                    id: tabId,
                    title: title,
                    action: action,
                    options: { ...options, _isTabManagerCall: true },
                });
                
                console.log('[TabManager] Current tabs:', this.state.tabs.length);
                console.log('[TabManager] Active tab:', this.state.activeTabId);
                
                return Promise.resolve();
            }
            
            console.log('[TabManager] Normal action execution');
            // 正常执行 action
            return originalDoAction(action, options);
        };
    }

    addTab(tabData) {
        console.log('[TabManager] addTab called:', tabData);
        // 检查是否已经有相同的标签页（基于 action）
        const actionKey = this._getActionKey(tabData.action);
        const existingTab = this.state.tabs.find(tab => 
            this._getActionKey(tab.action) === actionKey
        );
        
        if (existingTab) {
            console.log('[TabManager] Tab already exists, activating:', existingTab.id);
            // 如果已存在，激活它
            this.state.activeTabId = existingTab.id;
        } else {
            console.log('[TabManager] Adding new tab:', tabData.id);
            // 添加新标签页
            this.state.tabs.push(tabData);
            this.state.activeTabId = tabData.id;
            console.log('[TabManager] Total tabs now:', this.state.tabs.length);
        }
    }

    _getActionKey(action) {
        if (typeof action === 'object') {
            // 基于关键属性生成唯一键
            return JSON.stringify({
                type: action.type,
                res_model: action.res_model,
                res_id: action.res_id,
                view_mode: action.view_mode,
                xml_id: action.xml_id,
            });
        }
        return String(action);
    }

    closeTab(tabId, ev) {
        if (ev) {
            ev.stopPropagation();
        }
        
        const index = this.state.tabs.findIndex(tab => tab.id === tabId);
        if (index === -1) return;
        
        this.state.tabs.splice(index, 1);
        
        // 如果关闭的是当前标签页，激活相邻的标签页
        if (this.state.activeTabId === tabId) {
            if (this.state.tabs.length > 0) {
                const newIndex = Math.max(0, index - 1);
                this.state.activeTabId = this.state.tabs[newIndex].id;
            } else {
                this.state.activeTabId = null;
            }
        }
    }

    activateTab(tabId) {
        this.state.activeTabId = tabId;
    }

    isTabActive(tabId) {
        return this.state.activeTabId === tabId;
    }

    get hasTabs() {
        const result = this.state.tabs.length > 0;
        console.log('[TabManager] hasTabs:', result, 'count:', this.state.tabs.length);
        return result;
    }
    
    getActiveTab() {
        return this.state.tabs.find(tab => tab.id === this.state.activeTabId);
    }
}

// 注册到主组件
// TabManager 已集成到 WebClient 中，不再作为独立组件注册
// 此文件保留以备将来可能的独立使用

